#include "change64.h"

int binary[1024] = {0};  //暂存字符串ASCII码的二进制
char base64[65] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"};  //base64转换表
char change[1024] = {0};   //base64加密后字符串
int flag = 0;
int flag_change = 0;

void atob(int change_num)
{
	int temp[8] = {0}, i = 7;
	while(change_num)
	{
		temp[i--] = change_num % 2;
		change_num /= 2;
	}
	for(i = 0; i < 8; i++)
	{
		binary[flag++] = temp[i];
	}
	return;
}
void btoa(int len)
{
	int i, j, temp;
	for(i = 0; i < flag; i+=6)
	{
		temp = 0;
		for(j = i; j < i+6; j++)
		{
			temp = temp*2 + binary[j];
		}
		change[flag_change++] = base64[temp];	
	}
	if(len == 0)
	{
		return;
	}
	else if(len == 1)
	{
		strcat(change, "==");
	}
	else
	{
		strcat(change, "=");
	}
	return;
}
void to64(char *str)
{
	flag = 0;
	flag_change = 0;
	memset(change, 0, sizeof(change));
	int i;
	int len = strlen(str) % 3;
	for(i = 0; i < strlen(str); i++)
	{
		atob(str[i]);
	}
	if(len != 0)
	{	
		if(strlen(str)%3  == 1)
		{
			flag += 4;
		}
		else
		{
			flag += 2;
		}
	}
	btoa(len);
}
